package elasticsearch;

import io.vertx.core.json.JsonObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

public class DemoElasticSearch {

    public static void main(String[] args) {
        //初始化
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        // 使用elasticserach exporter导出流程的结果
        // 过滤条件：
        // "bpmnElementType":"END_EVENT"
        // "intent":"ELEMENT_COMPLETED"
        // "workflowInstanceKey":2251799814748844
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder
                .query(QueryBuilders
                        .boolQuery()
                        .must(QueryBuilders.matchQuery("value.bpmnElementType", "END_EVENT"))
                        .must(QueryBuilders.matchQuery("intent", "ELEMENT_COMPLETED"))
                        .must(QueryBuilders.matchQuery("value.workflowInstanceKey", 2251799814748844L)));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse;
        long totalHits = 0;
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            totalHits = searchResponse.getHits().getTotalHits();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (totalHits == 0) {
            System.out.println("当前流程没有执行完成");
        } else {
            //结果查询：
            // "name":"c"
            // "workflowInstanceKey":2251799814748844
            searchSourceBuilder
                    .query(QueryBuilders
                            .boolQuery()
                            .must(QueryBuilders.matchQuery("value.name", "c"))
                            .must(QueryBuilders.matchQuery("value.workflowInstanceKey", 2251799814748844L)));
            searchRequest.source(searchSourceBuilder);
            String result = null;
            try {
                searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
                JsonObject data = new JsonObject(searchResponse.getHits().getHits()[0].getSourceAsString());
                result = data.getJsonObject("value").getString("value");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("流程执行完成。最终结果为：" + result);
        }
        //关闭
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
